﻿using Core.DomainServices;
using Infrastructure.DomainServices;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ExcelViewer
{
    /// <summary>
    /// This is a sample read excel file using ExcelDataReader.2.1.2.3 library.
    /// If you have any questions let me know, my email: bin.nguyen.van@gmail.com
    /// </summary>
    public partial class frmMain : Form
    {
        private IDataRepository repository;
        private ILoggerService logger;
        private DataSet ds;
        private DataTable sheet;
        public frmMain()
        {
            InitializeComponent();
            gridDataSouce.DataBindingComplete +=gridDataSouce_DataBindingComplete;
            
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            logger = new FileLogger();
            repository = new ExcelRepository(logger);
            string path = Directory.GetCurrentDirectory().Replace("bin" + Path.DirectorySeparatorChar + "Debug", "DataSample") + Path.DirectorySeparatorChar + "TemplateData.xlsx";
            txtFileName.Text = path;
            BindData(txtFileName.Text);

        }

        private void BindData(string path)
        {
            ds = repository.ReadData(path);
            var sheetNames = repository.GetSheetNames(ds);
            cboSheetNames.DataSource = sheetNames;
            sheet = repository.GetItemsBySheetName(ds, cboSheetNames.SelectedValue.ToString());
            gridDataSouce.DataSource = sheet;
        }

        private void cboSheetNames_SelectedIndexChanged(object sender, EventArgs e)
        {
            sheet = repository.GetItemsBySheetName(ds, cboSheetNames.SelectedValue.ToString());
            gridDataSouce.DataSource = sheet;
        }


        protected void gridDataSouce_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            lblTotal.Text = "Total items: " + sheet.Rows.Count;
        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {

        }

        private void btnSelectedFile_Click(object sender, EventArgs e)
        {

            DialogResult result = openExcelFile.ShowDialog();

            if (result == DialogResult.OK)
            {
                txtFileName.Text = openExcelFile.FileName;
                BindData(txtFileName.Text);
            }
        }
    }
}
